package class3;


import common.ListNode;
import common.ListNodeUtils;

/**
 * 两个链表相加：
 * 9 -> 3 -> 7
 * 6 -> 3
 * 返回： 1 -> 0 -> 0 -> 0
 */
public class Code07_LinkedAdd2 {
    public static void main(String[] args) {
        ListNode head1 = ListNodeUtils.getLinked(9, 3, 7);
        ListNode head2 = ListNodeUtils.getLinked(6, 3);
        ListNode ans = addTwoNumbers(head1, head2);

        ListNodeUtils.print(ans);
    }


    public static ListNode addTwoNumbers(ListNode head1, ListNode head2) {
        ListNode cur1 = reverse(head1);
        ListNode cur2 = reverse(head2);
        ListNode ans = new ListNode(0);
        ListNode tail = ans;
        int curVal = 0;
        int c = 0;
        while (cur1 != null && cur2 != null) {
            int n = cur1.val + cur2.val + c;
            c = n / 10;
            tail.next = new ListNode(n % 10);
            tail = tail.next;
            cur1 = cur1.next;
            cur2 = cur2.next;
        }

        while (cur1 != null) {
            int n = cur1.val + c;
            c = n / 10;
            tail.next = new ListNode(n % 10);
            tail = tail.next;
            cur1 = cur1.next;
        }

        while (cur2 != null) {
            int n = cur2.val + c;
            c = n / 10;
            tail.next = new ListNode(n % 10);
            tail = tail.next;
            cur2 = cur2.next;
        }
        if(c==1){
            tail.next = new ListNode(1);
        }
        ans = ans.next;
        ans = reverse(ans);
        return ans;
    }

    // 求链表长度
    public static ListNode reverse(ListNode head) {
        ListNode next;
        ListNode pre = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

}
